package com.example.springboot3demo.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {

    // 算法名称
    private static final String ALGORITHM = "AES";
    // 加密模式和填充方式
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    /**
     * AES加密方法
     * @param plaintext 明文
     * @param secretKey 密钥（必须16/24/32字节，对应AES-128/192/256）
     * @return 加密后字符串（格式：Base64(IV) + "|" + Base64(密文)）
     */
    public static String encrypt(String plaintext, String secretKey) throws Exception {
        // 生成随机IV（初始化向量）
        byte[] iv = new byte[16];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(iv);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // 转换密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);

        // 加密
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

        // 将IV和密文分别进行Base64编码并拼接
        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        String ciphertextBase64 = Base64.getEncoder().encodeToString(encryptedBytes);

        return ivBase64 + "|" + ciphertextBase64;
    }

    /**
     * AES解密方法
     * @param encryptedData 加密数据（格式：Base64(IV) + "|" + Base64(密文)）
     * @param secretKey 密钥（必须与加密时相同）
     * @return 明文
     */
    public static String decrypt(String encryptedData, String secretKey) throws Exception {
        // 分割IV和密文
        String[] parts = encryptedData.split("\\|", 2);
        if (parts.length != 2) {
            throw new IllegalArgumentException("加密数据格式错误");
        }

        // 解码IV和密文
        byte[] iv = Base64.getDecoder().decode(parts[0]);
        byte[] ciphertext = Base64.getDecoder().decode(parts[1]);

        // 转换密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // 解密
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(ciphertext);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            // 密钥（必须32字节 = 256位）
            String secretKey = "0123456789abcdef0123456789abcdef";
            String plaintext = "SELECT * FROM users WHERE id = 1";

            // 加密
            String encrypted = encrypt(plaintext, secretKey);
            System.out.println("加密后: " + encrypted);

            // 解密
            String decrypted = decrypt(encrypted, secretKey);
            System.out.println("解密后: " + decrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
